<?php
/**
 * Description: 申请退款
 * User: devforma
 * Date: 16/2/25
 * Time: 18:21
 */

class ApplyRefund implements iController {

    const EXPRESS_FEE = 30;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {

        global $cmsdb;

        if (validateUser($queryArgs) !== 1 || empty($queryArgs['order_id'])
            || !filter_var($queryArgs['order_id'], FILTER_VALIDATE_INT) || empty($queryArgs['reason'])) {
            return genOutput(1000);
        }

        $exists = $cmsdb->getRow('SELECT `id`, `status` FROM `refund_orders` WHERE `order_id`=:oid', [':oid' => $queryArgs['order_id']]);
        if ($exists && $exists->status == 1) //        //已存在退款记录且退款成功
            return genOutput(1);

        //获取购买记录详情
        $sql = 'SELECT p.id, p.product_id, p.order_id, p.user_id, o.create_time, c.course_name, o.app_type, o.platform,
        o.price, c.material_fee, c.refund_deadline, c.need_address, o.platform_order
        FROM `relation_user_product` AS p, `original_orders` AS o, `data_live_course` AS c
        WHERE p.order_id=o.order_id AND p.product_id=c.id AND p.order_id=:oid AND p.user_id=:uid AND p.product_type="zhiboke" AND o.price>0';

        $orderInfo = $cmsdb->getRow($sql, array(':oid' => $queryArgs['order_id'], ':uid' => $queryArgs['user_id']));
        if (empty($orderInfo)) {
            return genOutput(1000);
        }

        //已经过了退款期限
        if (strtotime($orderInfo->refund_deadline) <= time()) {
            return genOutput(1000);
        }

        //计算退款金额
        $refundFee = $orderInfo->price;
        $extraInfo = '';

        if ($orderInfo->need_address) { //该课程会邮寄材料

            //检测物流信息
            $expressStatus = $this->getExpressStatus($orderInfo->id);

            if ($expressStatus == 1) { //已邮寄
                //构建退款说明信息
                $extraInfo = json_encode(array(
                    'material_fee' => $orderInfo->material_fee,
                    'express_fee' => self::EXPRESS_FEE
                ));

                $refundFee = $orderInfo->price - $orderInfo->material_fee - self::EXPRESS_FEE;
            }

        }

        if ($refundFee <= 0) {
            return genOutput(1001);
        }

        if ($exists) {
            $result = $cmsdb->update('refund_orders', array(
                'order_id' => $orderInfo->order_id,
                'user_id' => $orderInfo->user_id,
                'course_id' => $orderInfo->product_id,
                'create_time' => date('Y-m-d H:i:s'),
                'refund_fee' => $refundFee,
                'status' => 2,
                'status_code' => '',
                'app_type' => $orderInfo->app_type,
                'platform' => $orderInfo->platform,
                'refund_batch_no' => '',
                'total_fee' => $orderInfo->price,
                'platform_order' => $orderInfo->platform_order,
                'reason' => $queryArgs['reason'],
                'extra_info' => $extraInfo
            ), ['id' => $exists->id]);
        } else {
            $result = $cmsdb->insert('refund_orders', array(
                'order_id' => $orderInfo->order_id,
                'user_id' => $orderInfo->user_id,
                'course_id' => $orderInfo->product_id,
                'create_time' => date('Y-m-d H:i:s'),
                'refund_fee' => $refundFee,
                'status' => 2,
                'status_code' => '',
                'app_type' => $orderInfo->app_type,
                'platform' => $orderInfo->platform,
                'refund_batch_no' => '',
                'total_fee' => $orderInfo->price,
                'platform_order' => $orderInfo->platform_order,
                'reason' => $queryArgs['reason'],
                'extra_info' => $extraInfo
            ));
        }

        //申请退款需要将物流状态改为退款中
        if ($result) {
            if ($orderInfo->need_address)
                $cmsdb->update('express_tasks', array('status' => 3), array('rup_id' => $orderInfo->id));

            //更新邀请码使用记录状态为退课
            $cmsdb->update('order_invites', array('status' => 0),
                array('user_id' => $orderInfo->user_id, 'order_id' => $orderInfo->order_id));

            return genOutput(1);
        }

        return genOutput(1001);
    }

    /**
     * 获取物流信息
     *
     * @param $rupId
     * @return int 0为未处理或退款中, 1为处理中
     */
    private function getExpressStatus($rupId) {
        global $cmsdb;

        $express = $cmsdb->getRow('SELECT `id`, `status` FROM `express_tasks` WHERE `rup_id`=:rupid', array(':rupid' => $rupId));
        if (!empty($express) && ($express->status == 1 || $express->status == 2)) { //如果有物流信息且已处理或已寄送,则需要在退款申请时处理退款金额
            return 1;
        }

        return 0;
    }
}